<!-- 回执信息 -->
<template>
	<uni-popup ref="receiptInformation" type="dialog" :mask-click="false">
		<view class="popup-content">
			<view class="title">
				<uni-icons class="icon" type="info-filled" size="24" color="green"></uni-icons>
				<text>填写信息</text>
			</view>
			<view class="content">
				<!-- 基础信息 -->
				<template>
					<view class="item" v-if="props.receiptContent?.name">
						<view class="left" :class="{ require: props.receiptContent?.name?.isMust }">姓名:</view>
						<view class="right">
							<input :value="props.value.name" @change="(e)=>inputChangeHandle(e,'name')" placeholder="请输入姓名" />
						</view>
					</view>
					<view class="item" v-if="props.receiptContent?.phone">
						<view class="left" :class="{ require: props.receiptContent?.phone?.isMust }">手机号:</view>
						<view class="right">
							<input :value="props.value.phone" @change="(e)=>inputChangeHandle(e,'phone')" placeholder="请输入手机号" />
						</view>
					</view>
					<view class="item" v-if="props.receiptContent?.idCard">
						<view class="left" :class="{ require: props.receiptContent?.idCard?.isMust }">身份证号:</view>
						<view class="right">
							<input :value="props.value.idCard" @change="(e)=>inputChangeHandle(e,'idCard')" placeholder="请输入身份证号" />
						</view>
					</view>
					<view class="item" v-if="props.receiptContent?.address">
						<view class="left" :class="{ require: props.receiptContent?.address?.isMust }">地址:</view>
						<view class="right">
							<picker mode="multiSelector" :range="vdata.range" range-key="text" :value="vdata.rangeIndex"
								@columnchange="columnchange" @change="changeHandle">
								<text v-if="vdata.rangeValue?.length < 4" style="color: #808080;">请选择地址</text>
								<text v-else>{{ `${vdata.rangeValue[0]}/${vdata.rangeValue[1]}/${vdata.rangeValue[2]}/${vdata.rangeValue[3] || '暂未选择'}` }}</text>
							</picker>
						</view>
					</view>
					<view class="item" v-if="props.receiptContent?.address">
						<view class="left" :class="{ require: props.receiptContent?.address?.isMust }">详细地址:</view>
						<view class="right">
							<input :value="props.value.detailAddress" @change="(e)=>inputChangeHandle(e,'detailAddress')" placeholder="请输入详细地址" />
						</view>
					</view>
					<view class="item" v-if="props.receiptContent?.bankImg">
						<view class="left" :class="{ require: props.receiptContent?.bankImg?.isMust }">银行卡照片:</view>
						<view class="right">
							<button v-if="!props.value.bankImg" plain @click="onChooseAvatar">点击上传银行卡照片</button>
							<image v-if="props.value.bankImg" @click="clickImg(props.value.bankImg)" :src="props.value.bankImg" mode="aspectFill"></image>
						</view>
					</view>
					<view class="item" v-if="props.receiptContent?.bankCard">
						<view class="left" :class="{ require: props.receiptContent?.bankCard?.isMust }">银行卡号:</view>
						<view class="right">
							<input :value="props.value.bankCard" @change="(e)=>inputChangeHandle(e,'bankCard')" placeholder="请输入银行卡号" />
						</view>
					</view>
					<view class="item" v-if="props.receiptContent?.deposit">
						<view class="left" :class="{ require: props.receiptContent?.deposit?.isMust }">额度:</view>
						<view class="right">
							<input :value="props.value.deposit" @change="(e)=>inputChangeHandle(e,'deposit')" placeholder="请输入提额额度" />
						</view>
					</view>
					<template v-if="props.receiptContent?.date">
						<view v-if="props.receiptType?.includes(3)" class="item">
							<view class="left" :class="{ require: props.receiptContent?.date?.isMust }">开卡日期:</view>
							<view class="right">
								<picker mode="date" @change="(e) => dateChange(e,'openDate')" :value="props.value.openDate">
									<text v-if="!props.value.openDate" style="color: #808080;">请选择开卡日期</text>
									<text v-else>{{ props.value.openDate }}</text>
								</picker>
							</view>
						</view>
						<view v-if="props.receiptType?.includes(4)" class="item">
							<view class="left" :class="{ require: props.receiptContent?.date?.isMust }">提额日期:</view>
							<view class="right">
								<picker mode="date" @change="(e) => dateChange(e,'depositDate')" :value="props.value.depositDate">
									<text v-if="!props.value.depositDate" style="color: #808080;">请选择提额日期</text>
									<text v-else>{{ props.value.depositDate }}</text>
								</picker>
							</view>
						</view>
					</template>
					<view class="item" v-if="props.receiptContent?.pension">
						<view class="left" :class="{ require: props.receiptContent?.pension?.isMust }">养老金账户号:</view>
						<view class="right">
							<input :value="props.value.pension" @change="(e)=>inputChangeHandle(e,'pension')" placeholder="请输入养老金账户号" />
						</view>
					</view>
					<view class="item" v-if="props.receiptContent?.mchNo">
						<view class="left" :class="{ require: props.receiptContent?.mchNo?.isMust }">商户号:</view>
						<view class="right">
							<input :value="props.value.mchNo" @change="(e)=>inputChangeHandle(e,'mchNo')" placeholder="请输入商户号" />
						</view>
					</view>
				</template>
			</view>
			<view style="width: 100%; display: flex; padding: 0 40rpx; box-sizing: border-box; gap: 40rpx;">
				<text class="but" style="background-color: #FF5A5A;"
					@click="()=>{ receiptInformation.close() }">取消</text>
				<text class="but" @click="complete">确认</text>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import { ref, defineProps, defineEmits, defineExpose, onMounted, reactive, getCurrentInstance } from 'vue'
	import { $ossFilesForm, } from '@/http/apiManager.js'
	import storageManage from '@/util/storageManage.js'
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties
	import { checkPhone, checkBankCard, checkIdCard } from '@/util/validate.js'
	// #ifdef MP-YHDD
	import activityAddress from '@/components/applyJson/activityAddressCc.json'
	// #endif
	// #ifndef MP-YHDD
	import activityAddress from '@/components/applyJson/activityAddressZz.json'
	// #endif
	
	const receiptInformation = ref()
	
	const props = defineProps({
		// 回执内容
		value: {
			type: Object,
			default: {
				name: '',
				phone: '',
				idCard: '',
				address: '',
				detailAddress: '',
				// 开卡\手机银行\提额回执
				bankImg: '',	// 银行卡照片
				bankCard: '',	// 银行卡号
				openDate: '',	// 开卡日期
				depositDate: '',	// 提额日期
				deposit: '',	// 额度
				pension: '',	// 养老金账户号
				mchNo: '',	// 商户号
			}
		},
		// 回执类型	0 基础信息 1 手机银行 2 快捷支付 3 开卡 4 提额
		receiptType: {
			type: String,
			default: ''
		},
		// PC后台配置回执规则
		receiptContent: {
			type: Object,
			default: {}
		}
	})
	
	// 更新回执内容
	const emits = defineEmits(['update:value','complete'])
	
	onMounted(() => {
		// 初始化地址 多选列 选项
		addressHandle()
	})
	
	const vdata = reactive({
		range: [], // 地址信息 原始数据
		rangeIndex: [0, 0, 0, 0], // 选择的地址信息
		rangeValue: [], // 对应值
	})
	
	
	// input change
	function inputChangeHandle(e,key){
		if(e.detail.value !== props.value[key]){
			if(key === 'detailAddress'){
				emits('update:value',{ ...props.value, [key]: e.detail.value, address: props.value.address + e.detail.value })
			}else{
				emits('update:value',{ ...props.value, [key]: e.detail.value })
			}
		}
	}
	/**
	 * 地址选择单列事件
	 */
	const columnchange = ({ detail }) => {
		addressHandle(detail)
	}
	/**
	 * 地址处理函数
	 * 接受参数
	 * 变化的列 colIndex 
	 * 根据变化的列 去取他的children 并赋值在第四列（也就是只有第三列改变的时候 才会影响到第四列的值）
	 */
	const addressHandle = (detail) => {
		if (!detail) {
			vdata.range = [
				[{
					text: activityAddress.text
				}],
				[{
					text: activityAddress.children[0].text
				}], activityAddress.children[0].children, activityAddress.children[0].children[0].children
			]
		} else {
			const { column, value: colIndex } = detail
			if (column === 2) {
				const fourthCol = activityAddress.children[0].children[colIndex].children // 除了要更新数据列表 还要更新下标
				vdata.range[3] = fourthCol
				vdata.rangeIndex = [0, 0, colIndex, 0]
			}
		}
	}
	/**
	 * 地址选择事件
	 */
	const changeHandle = ({ detail }) => {
		detail.value.forEach((item, index) => {
			vdata.rangeValue[index] = vdata.range[index][detail.value[index]].text
		})
		vdata.rangeIndex = detail.value
		emits('update:value',{ ...props.value, address: vdata.rangeValue[0] + vdata.rangeValue[1] + vdata.rangeValue[2] + (vdata.rangeValue[3] || '') + props.value.detailAddress })
	}
	
	/**
	 * 银行卡照片上传相关代码
	 */
	function onChooseAvatar() {
		uni.chooseImage({
			count: 1, //可选择数量，默认9
			sizeType: ['compressed'], //只能上传压缩图
			sourceType: ['album', 'camera'], //从相册选择或从使用相机
			success: async (res) => {
				if (res.tempFiles[0].size > 10 * 1024 * 1000) { //上传图片大小限制
					uni.showToast({
						title: "照片大小不能10MB",
						icon: "none"
					})
					return
				}
				let url1 = res.tempFilePaths[0];
				if (url1) {
					uni.getFileSystemManager().getFileInfo({
						filePath: url1,
						success({
							size
						}) {
							$ossFilesForm({
								bizType: 'user',
								sourceFileName: getFileName(url1),
								sourceFileSize: size
							}).then(({
								bizData
							}) => {
								let url = bizData.formActionUrl
								let ossFileUrl = bizData.ossFileUrl
								// 调用图片上传方法
								uploadImg(url1, url, bizData.formParams, ossFileUrl)
							})
						}
					})
				}
			}
		});
	}
	
	/**
	 * 获取文件名称
	 */
	function getFileName(name) {
		if (!name) {
			return name
		}
		return name.substring(name.lastIndexOf('/') + 1)
	}
	
	function uploadImg(tempFilePath, url, formParams, ossFileUrl) {
		const token = storageManage.token()
		uni.showLoading({
			title: '上传中...'
		});
		//循环上传图片
		uni.uploadFile({
			url: url,
			filePath: tempFilePath,
			name: 'file',
			header: {
				'Content-Type':'multipart/form-data'
			},
			formData: formParams,
			// 代表完成的函数 注：此处可以传入三个函数  success （成功）/ fail（失败） / complete （完成）
			complete(res) {
				uni.hideLoading()
				if (res.statusCode != 200 && res.statusCode != 204) {
					$infoBox.toast('请求失败，请重试')
					return
				}
				emits('update:value',{ ...props.value, bankImg: ossFileUrl })
			}
		})
	}
	
	
	// 点击图片出现预览图片
	const clickImg = (item) => {
		uni.previewImage({
			urls: [item], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
			current: '', // 当前显示图片的http链接，默认是第一个
			success: function(res) {},
			fail: function(res) {},
			complete: function(res) {},
		})
	
	}
	/**
	 * 日期选择事件
	 */
	function dateChange(e,key){
		if(e.detail.value !== props.value[key]){
			emits('update:value',{ ...props.value, [key]: e.detail.value })
		}
	}
	// 完成
	function complete(){
		// 校验数据
		const { name, phone, idCard, address, bankImg, bankCard, deposit, date, pension, mchNo } = props.receiptContent
		const {
			name:nameValue,
			phone:phoneValue,
			idCard:idCardValue,
			address:addressValue,
			detailAddress:detailAddressValue,
			bankImg:bankImgValue,
			bankCard:bankCardValue,
			deposit:depositValue,
			openDate:openDateValue,
			depositDate:depositDateValue,
			pension: pensionValue,
			mchNo: mchNoValue,
		} = props.value
		if(!nameValue && name && name?.isMust){
			$infoBox.toast('请输入姓名')
			return
		}
		if((!phoneValue || !checkPhone(phoneValue)) && phone && phone?.isMust){
			$infoBox.toast('请输入正确的手机号')
			return
		}
		if((!idCardValue || !checkIdCard(idCardValue)) && idCard && idCard?.isMust){
			$infoBox.toast('请输入正确的身份证号')
			return
		}
		if((!addressValue || !detailAddressValue) && address && address?.isMust){
			if(!addressValue){
				$infoBox.toast('请选择地址')
				return
			}
			if(!detailAddressValue){
				$infoBox.toast('请输入详细地址')
			}
			return
		}
		if(!bankImgValue && bankImg && bankImg?.isMust){
			$infoBox.toast('请上传银行卡照片')
			return
		}
		if((!bankCardValue || !checkBankCard(bankCardValue)) && bankCard && bankCard?.isMust){
			$infoBox.toast('请输入正确的银行卡号')
			return
		}
		if(!depositValue && deposit && deposit?.isMust){
			$infoBox.toast('请输入提额额度')
			return
		}
		if(!openDateValue && date && date?.isMust && props.receiptType?.includes(3)){
			$infoBox.toast('请选择开卡日期')
			return
		}
		if(!depositDateValue && date && date?.isMust && props.receiptType?.includes(4)){
			$infoBox.toast('请选择提额日期')
			return
		}
		if(!pensionValue && pension && pension?.isMust){
			$infoBox.toast('请输入养老金账户号')
			return
		}
		if(!mchNoValue && mchNo && mchNo?.isMust){
			$infoBox.toast('请输入养老金账户号')
			return
		}
		emits('complete')
	}
	// 打开弹窗
	function show(){
		// 数据重置
		vdata.rangeIndex = [0,0,0,0]
		vdata.rangeValue = []
		receiptInformation.value.open()
	}
	// 关闭弹窗
	function close(){
		receiptInformation.value.close()
	}
	// 暴露子组件属性方法
	defineExpose({
		show,
		close
	})
</script>

<style lang="less" scoped>
	:deep(.uni-popup .uni-popup__wrapper) {
		width: 75% !important;
		padding: 40rpx;
	}
	.popup-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40rpx;
		font-size: 26rpx;
		background-color: white;
		border-radius: 20rpx;
		letter-spacing: 1px;
		box-sizing: border-box;
		// width: 500rpx;
	
		.title {
			display: flex;
			justify-content: center;
			align-items: center;
			font-weight: bold;
			font-size: 32rpx;
			margin-bottom: 40rpx;
			width: 70%;
	
			.icon {
				margin-right: 15rpx;
			}
		}
	
		.content {
			width: 100%;
			margin-bottom: 15rpx;
	
			.item {
				display: flex;
				height: 80rpx;
				align-items: center;
				border-bottom: 1rpx solid #f0f0f0;
	
				.left {
					padding-right: 10rpx;
					flex-shrink: 0;
					
					&.require{
						&::before{
							content: '*';
							color: red;
						}
					}
				} 
	
				.right {
					flex-grow: 1;
					image {
						width: 120rpx;
						height: 60rpx;
						border-radius: 5rpx;
						vertical-align: -4px;
					}
					button{
						border: none;
						width: initial;
						color: #808080;
						padding: initial;
						line-height: initial;
						text-align: left;
						font-size: 26rpx;
					}
					text{
						white-space: nowrap;
					}
				}
			}
		}
	
		.but {
			font-size: 30rpx;
			color: white;
			border-radius: 40rpx;
			width: 80%;
			padding: 18rpx 0rpx;
			background-color: #24C789;
			margin-top: 30rpx;
			text-align: center;
			margin-bottom: 10rpx;
		}
	
	}
</style>